/**
 * 上传图片容器控件
 * @file UploaderContainer.js
 * @author chuzhenyang(chuzhenyang@baidu.com)
 */

define(function (require) {
    var u = require('underscore');
    var esui = require('esui');
    var lib = require('esui/lib');
    var InputControl = require('esui/InputControl');
    var eoo = require('eoo');
    var $ = require('jquery');
    var painters = require('esui/painters');

    /**
     * 上传图片容器控件
     *
     * @extends {InputControl}
     * @param {Object} options 初始化参数
     * @constructor
     */
    var UploaderContainer = eoo.create(
        InputControl,
        {
            /**
             * 控件类型,始终为`"UploaderContainer"`
             *
             * @type {string}
             * @readonly
             * @override
             */
            type: 'UploaderContainer',

            /**
             * 初始化参数
             *
             * @param {Object} [options] 构造函数传入的参数
             * @protected
             * @override
             */
            initOptions: function (options) {
                var properties = {
                    /**
                     * @property {number} [width=400]
                     *
                     * 默认宽度
                     */
                    width: 400,
                    /**
                     * @property {number} [height=200]
                     *
                     * 默认高度
                     */
                    height: 200,
                    /**
                     * @property {Array} [datasource=['']]
                     *
                     * CandidateArea的数据源
                     */
                    datasource: [],
                    /**
                     * @property {number} [limit=200]
                     *
                     * 默认可以上传的个数
                     */
                    limit: 9999,
                    /**
                     * @property {number} [typeName='图片']
                     *
                     * 默认上传的类型名称
                     */
                    typeName: '图片'

                };
                u.extend(properties, UploaderContainer.defaultProperties, options);

                if (!properties.datasource) {
                    properties.datasource = [];
                }

                this.setProperties(properties);
            },

            /**
             * 初始化DOM结构
             *
             * @protected
             * @override
             */
            initStructure: function () {
                var tpl = [
                    '<div class="${headClass}" id="${headId}">',
                        '<div class="${headInfoClass}">已经上传',
                        '<span id="${uploadedNumId}">0</span>',
                        '个${typeName}，还可以上传',
                        '<span id="${toUploadNumId}">${limit}</span>',
                        '个</div>',
                        '<span class="${deteteAllClass}" id="${deleteAllId}">${deleteAll}</span>',
                    '</div>',
                    '<div class="${bodyClass}" id="${bodyId}">',
                    '</div>'
                ].join('');
                var helper = this.helper;

                this.main.innerHTML = lib.format(
                    tpl,
                    {
                        headClass: helper.getPartClasses('head'),
                        headInfoClass: helper.getPartClasses('head-info'),
                        uploadedNumId: helper.getId('uploadedNum'),
                        toUploadNumId: helper.getId('toUploadNum'),
                        deleteAllId: helper.getId('deleteAll'),
                        limit: this.limit,
                        typeName: this.typeName,
                        deteteAllClass: helper.getPartClasses('delete-all'),
                        deleteAll: this.deleteAllText,
                        bodyClass: helper.getPartClasses('body'),
                        bodyId: helper.getId('body'),
                        headId: helper.getId('head')
                    }
                );
            },

            /**
             * 重渲染
             *
             * @method
             * @protected
             * @override
             */
            repaint: painters.createRepaint(
                InputControl.prototype.repaint,
                /**
                 * @property {Array} datasource
                 * @property {Array} selectedValue
                 *
                 * 数据源
                 */
                {
                    name: ['datasource'],
                    paint: function (container, datasource) {
                        if (datasource.length > container.limit) {
                            datasource.splice(0, container.limit);
                        }
                        $(container.helper.getPart('body')).empty();
                        u.each(datasource, u.bind(renderSingleLine, container));
                        resetShowNum.call(container);
                    }
                },
                /**
                 * @property {Number} width
                 * @property {Number} height
                 *
                 * 宽度和高度
                 */
                {
                    name: ['width', 'height'],
                    paint: function (container, width, height) {
                        $(container.main).width(width);
                        $(container.main).height(height);
                        var bodyHeight = $(container.main).height() - $(container.helper.getPart('head')).height();
                        $(container.helper.getPart('body')).height(bodyHeight);
                    }
                }
            ),

            /**
             * 初始化事件交互
             *
             * @protected
             * @override
             */
            initEvents: function () {

                // 为每一行列表添加选中的事件
                this.helper.addDOMEvent(
                    this.helper.getPart('body'),
                    'click',
                    '[data-role-type="line"]',
                    u.bind(function (event) {
                        var index = +$(event.currentTarget).attr('data-line-index');
                        this.fire('select', {value: this.get('datasource')[index]});
                        var selectedClass = this.helper.getPartClassName('line-selected');
                        $(this.helper.getPart('body')).children().removeClass(selectedClass);
                        $(event.currentTarget).addClass(selectedClass);
                    }, this)
                );

                // 每一个delete的button点击后删除其父节点，同时重置显示的数字
                this.helper.addDOMEvent(
                    this.helper.getPart('body'),
                    'click',
                    '[data-role-type="delete"]',
                    u.bind(function (event) {
                        var index = $(event.target).parents('[data-role-type="line"]').attr('data-line-index');
                        var datasource = this.get('datasource').concat([]);
                        datasource.splice(index, 1);
                        this.setProperties({datasource: datasource});
                        this.fire('deleted');
                        event.stopPropagation();
                    }, this)
                );

                // 删除全部事件
                this.helper.addDOMEvent(
                    this.helper.getPart('deleteAll'),
                    'click',
                    u.bind(function (event) {
                        this.setProperties({datasource: []});
                        this.fire('deleted');
                    }, this)
                );
            },

            /**
             * 添加新行
             *
             * @param {Array} sources 新添加的数据源
             */
            addLines: function (sources) {
                var datasource = this.get('datasource').concat(sources);
                this.setProperties({datasource: datasource});
            },

            /**
             * 获取目前所有的尺寸
             *
             * @return {Array}
             */
            getSizes: function () {
                return u.map($(this.main).find('[data-role-type="line"]'), function (line) {
                    return $(line).attr('data-line-size');
                });
            },

            /**
             * override
             *
             * @return {Array}
             */
            getRawValue: function () {
                return this.get('datasource');
            }
        }
    );

    /**
     * 默认属性值
     *
     * @type {Object}
     * @public
     */
    UploaderContainer.defaultProperties = {
        // 删除全部的文本
        deleteAllText: '删除全部'
    };

    /**
     * 渲染单行模板
     *
     * @param {Object} [source] 单行的数据源
     * @param {number} index 位置
     */
    function renderSingleLine(source, index) {
        var tpl = [
            '<div class="${lineClass}" data-role-type="line" data-line-url="${url}"',
                'data-line-size="${size}" data-line-index=${index}>',
                '<p class="${lineTitleClass}">${title}</p>',
                '<p class="${lineSizeClass}">${size}</p>',
                '<p class="${lineDeleteClass}"><span class="${deleteClass}" data-role-type="delete"></span></p>',
            '</div>'
        ].join('');
        var helper = this.helper;

        var addNode = lib.format(
            tpl,
            {
                lineClass: helper.getPartClasses('line'),
                lineTitleClass: helper.getPartClasses('line-title'),
                lineSizeClass: helper.getPartClasses('line-size'),
                deleteClass: helper.getIconClass('close'),
                lineDeleteClass: helper.getPartClasses('line-delete'),
                title: source.title,
                size: source.width + '*' + source.height,
                url: source.mediaPreviewUrl,
                index: index
            }
        );

        $(this.helper.getPart('body')).append(addNode);
    }

    function resetShowNum() {
        var linesNum = $(this.helper.getPart('body')).find('[data-role-type="line"]').length;
        $(this.helper.getPart('uploadedNum')).text(linesNum);
        $(this.helper.getPart('toUploadNum')).text(this.limit - linesNum);
    }

    esui.register(UploaderContainer);
    return UploaderContainer;
});
